iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
自我挑戰組

c 語言與 python 的30天之旅系列 第 24

Python 與 Magic Methods

  • 分享至 

  • xImage
  •  

魔術方法,也稱為「dunder」(雙底線)方法,為 Python 類別定義特殊行為,讓您實作加法、索引等自訂操作。

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age


def __str__(self):
        return f"Dog: {self.name}, Age: {self.age}"
    def __add__(self, other):
        return f"{self.name} and {other.name}"

上一篇
Python 與 Closures
系列文
c 語言與 python 的30天之旅24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言